package com.appspot.bibtable.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.bibtable.PMF;
import com.appspot.bibtable.UrlCollection;
import com.appspot.bibtable.model.UserInfo;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class CancelMembershipServlet extends HttpServlet
{
	private static final Logger logger = Logger.getLogger(CancelMembershipServlet.class.getName());

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		UserService service = UserServiceFactory.getUserService();
		

		if (service.isUserLoggedIn())
		{
			User user = service.getCurrentUser();

			PersistenceManager manager = PMF.get().getPersistenceManager();
			Transaction transaction = manager.currentTransaction();

			boolean activation = false;
			try
			{
				transaction.begin();
				UserInfo userInfo = UserInfo.getUserInfoOf(user, manager);
				int givenHash = Integer.parseInt(request.getParameter("key"));
				activation = userInfo.getKey().hashCode() == givenHash;
				if (activation)
				{
					manager.deletePersistent(userInfo);
				}
				transaction.commit();
			}
			finally
			{
				if (transaction.isActive())
				{
					logger.warning("Canceling membership of id:" + user.getUserId() + " failed.");
					transaction.rollback();
					response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
				}
				else if (activation)
				{
					logger.info("id:" + user.getUserId() + " has been unregistered.");
				}
				manager.close();
			}
		}
		else
		{
			logger.warning("Anonymous user.");
		}
		response.sendRedirect(UrlCollection.INDEX);
	}
}
